package com.hhf.rpa.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class FileUtils {

    /**
     * 递归创建目录
     * @param path 目录路径
     */
    public static void createDirectoriesRecursively(String path) {
        // 将字符串路径转换为Path对象
        Path dirPath = Paths.get(path);

        // 获取父路径
        Path parentPath = dirPath.getParent();

        // 如果父路径不为空，则递归创建父路径
        if (parentPath != null &&!parentPath.toFile().exists()) {
            createDirectoriesRecursively(parentPath.toString());
        }

        // 创建当前目录
        File dir = new File(dirPath.toUri());
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            if (created) {
                log.info("Directory created: " + dir.getAbsolutePath());
            } else {
                log.info("Failed to create directory: " + dir.getAbsolutePath());
            }
        } else {
            log.info("Directory already exists: " + dir.getAbsolutePath());
        }
    }

    /**
     * 计算给定文件的 MD5 值。
     *
     * @param path 文件路径
     * @return 文件的 MD5 值
     */
    public static String calculateMD5(Path path) {
        try (InputStream fis = Files.newInputStream(path)) {
            return calculateMD5(fis);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 计算给定文件流的 MD5 值。
     *
     * @param fis 文件流
     * @return 文件的 MD5 值
     */
    public static String calculateMD5(InputStream fis) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] byteArray = new byte[8192];
            int bytesCount;

            while ((bytesCount = fis.read(byteArray)) != -1) {
                digest.update(byteArray, 0, bytesCount);
            }

            byte[] bytes = digest.digest();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.length; i++) {
                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
